package com.wawei.seeds.common;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.wawei.seeds.R;
import com.wawei.seeds.views.ClipImageLayout;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class ClipImageActivity extends Activity implements View.OnClickListener {
    @InjectView(R.id.clip_image_layout)
    ClipImageLayout imageLayout;
    @InjectView(R.id.ok_button)
    View okBtn;
    @InjectView(R.id.cancle_button)
    View cancleBtn;

    public static final String RESULT_PATH = "crop_image";
    private static final String KEY = "path";
    private static final String TMP_PATH = "clip_temp.jpg";
    private static Bitmap bitmap_;

    public static void startActivity(Fragment fragment, String path, int code) {
        Intent intent = new Intent(fragment.getActivity(), ClipImageActivity.class);
        intent.putExtra(KEY, path);
        fragment.startActivityForResult(intent, code);
    }

    public static void startActivity(Fragment fragment, Bitmap bitmap, int code) {
        bitmap_ = bitmap;
        Intent intent = new Intent(fragment.getActivity(), ClipImageActivity.class);
        fragment.startActivityForResult(intent, code);
    }

    public static void startActivity(Activity activity, String path, int code) {
        Intent intent = new Intent(activity, ClipImageActivity.class);
        intent.putExtra(KEY, path);
        activity.startActivityForResult(intent, code);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clip_image);
        ButterKnife.inject(this);

        Bitmap bitmap = bitmap_;
        int degreee = 0;

        if (bitmap == null) {
            try {
                String path = getIntent().getStringExtra(KEY);

                bitmap = createBitmap(path);

                // 有的系统返回的图片是旋转了，有的没有旋转，所以处理
                degreee = readBitmapDegree(path);
            } catch (Exception e) {
                e.printStackTrace();
                Intent intent = new Intent();
                setResult(RESULT_CANCELED, intent);
                finish();
            }
        }
        if (bitmap != null) {
            if (degreee == 0) {
                imageLayout.setImageBitmap(bitmap);
                //imageLayout.setImageBitmap(rotateBitmap(degreee + 90, bitmap));
            } else {
                imageLayout.setImageBitmap(rotateBitmap(degreee, bitmap));
            }
        } else {
            Intent intent = new Intent();
            setResult(RESULT_CANCELED, intent);
            finish();
        }

        okBtn.setOnClickListener(this);
        cancleBtn.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bitmap_ = null;
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.ok_button) {
            Bitmap bitmap = imageLayout.clip();

            String path = this.getFilesDir() + File.separator + TMP_PATH;
            saveBitmap(bitmap, path);

            Intent intent = new Intent();
            intent.putExtra(RESULT_PATH, path);
            setResult(RESULT_OK, intent);
        } else {
            Intent intent = new Intent();
            setResult(RESULT_CANCELED, intent);
        }

        finish();
    }

    private void saveBitmap(Bitmap bitmap, String path) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;//个人喜欢从100开始,
        int step = 10;
        int maxSize = 200;
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        // 大于100k继续压缩
        while (baos.toByteArray().length / 1024 > maxSize && options >= step) {
            baos.reset();
            options -= step;
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }

        Log.d("test", "======size:" + (baos.toByteArray().length / 1024));

        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }

        FileOutputStream fOut = null;
        try {
            f.createNewFile();
            fOut = new FileOutputStream(f);
            fOut.write(baos.toByteArray());
            fOut.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fOut != null)
                    fOut.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 创建图片
     *
     * @param path
     * @return
     */
    private Bitmap createBitmap(String path) {
        if (path == null) {
            return null;
        }

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = 1; // 图片大小，与原图一样
        opts.inJustDecodeBounds = false; // 这里一定要将其设置回false，因为之前我们将其设置成了true, true时只读边,不读内容
        // 同时设置内存不够时图片会被回收
        //opts.inPurgeable = true;
        //opts.inInputShareable = true;
        opts.inDither = false; // 是否抖动,失真
        FileInputStream is = null;
        Bitmap bitmap = null;
        try {
            is = new FileInputStream(path);
            bitmap = BitmapFactory.decodeFileDescriptor(is.getFD(), null, opts);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                    is = null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bitmap;
    }

    // 读取图像的旋转度
    private int readBitmapDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(
                    ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    // 旋转图片
    private Bitmap rotateBitmap(int angle, Bitmap bitmap) {
        // 旋转图片 动作
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        // 创建新的图片
        Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, false);
        return resizedBitmap;
    }
}
